package com.ktg.mes.md.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import com.ktg.common.core.domain.model.SqlResult;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.mes.md.domain.ZuZhuangUse;
import com.ktg.mes.unit.other.SQLListenerInterface;
import com.ktg.mes.unit.other.SQLListenerType;
import com.ktg.mes.wm.domain.WmIssueLine;
import com.ktg.mes.wm.domain.WmItemRecptLine;
import com.ktg.mes.wm.service.IWmIssueLineService;
import com.ktg.mes.wm.service.IWmItemRecptLineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.md.mapper.MdProductStatisticsBomMapper;
import com.ktg.mes.md.domain.MdProductStatisticsBom;
import com.ktg.mes.md.service.IMdProductStatisticsBomService;



/**
 * 产品的统计分类BOMService业务层处理
 *
 * @author byteco
 * @date 2023-02-22
 */
@Service
public class MdProductStatisticsBomServiceImpl extends ServiceImpl<MdProductStatisticsBomMapper, MdProductStatisticsBom> implements IMdProductStatisticsBomService
{

    @Autowired
    private IWmIssueLineService wmIssueLine;

    @Autowired
    private IWmItemRecptLineService itemRecptLineService;


    /**
     * 查询产品的统计分类BOM
     *
     * @param entity 产品的统计分类BOM
     * @param page 分页对象
     * @return 产品的统计分类BOM
     */
    @Override
    public IPage<MdProductStatisticsBom> queryPageList(MdProductStatisticsBom entity, Page<MdProductStatisticsBom> page) {
        QueryWrapper<MdProductStatisticsBom> lqw = new QueryWrapper<MdProductStatisticsBom>(entity);
        lqw.orderByDesc("quantity");
        IPage<MdProductStatisticsBom> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询产品的统计分类BOM
     *
     * @param entity 产品的统计分类BOM
     * @return 产品的统计分类BOM
     */
    @Override
    public List<MdProductStatisticsBom> queryList(MdProductStatisticsBom entity) {
        QueryWrapper<MdProductStatisticsBom> lqw = new QueryWrapper<MdProductStatisticsBom>(entity);
        lqw.orderByDesc("quantity");
        return this.list(lqw);
    }

    public MdProductStatisticsBom getInfo(Long id)
    {
        return this.getById(id);
    }


    /**
     * 新增产品的统计分类BOM
     *
     * @param entity 产品的统计分类BOM
     * @return 结果
     */
    @Override
    public void insert(MdProductStatisticsBom entity)
    {
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        this.save(entity);
    }

    /**
     * 修改产品的统计分类BOM
     *
     * @param entity 产品的统计分类BOM
     * @return 结果
     */
    @Override
    public boolean update(MdProductStatisticsBom entity)
    {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }

    /**
     * 批量删除产品的统计分类BOM
     *
     * @param bomIds 需要删除的产品的统计分类BOM主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] bomIds)
    {

        return this.removeByIds(Arrays.asList(bomIds));
    }

    /**
     * 删除产品的统计分类BOM信息
     *
     * @param bomId 产品的统计分类BOM主键
     * @return 结果
     */
    @Override
    public boolean delete(Long bomId)
    {
        return this.removeById(bomId);
    }

    private LambdaQueryWrapper<MdProductStatisticsBom> buildQueryWrapper(MdProductStatisticsBom entity) {
        LambdaQueryWrapper<MdProductStatisticsBom> lqw = Wrappers.lambdaQuery();
                    lqw.eq(entity.getStatisticsId() != null, MdProductStatisticsBom::getStatisticsId, entity.getStatisticsId());
        return lqw;
    }


    /**
     * 组装入库，用料材料判断
     * @param type
     * @param oldObj
     * @param newObj
     * @return
     */
    @SQLListenerInterface(tableName = "wm_issue_line",listerType = {SQLListenerType.AfterAll})
    public SqlResult wmIssueLineListener(SQLListenerType type, WmIssueLine oldObj, WmIssueLine newObj) {
        try {
            //组装入库，用料材料判断
            if (oldObj !=null && newObj != null){
                if (oldObj.getAssembleIdToItemRecptLineId() == null
                        && newObj.getAssembleIdToItemRecptLineId() == null){
                    return SqlResult.ok(null,newObj);
                }

                if (oldObj != null && newObj != null && oldObj.getAssembleIdToItemRecptLineId().longValue() != newObj.getAssembleIdToItemRecptLineId().longValue()){
                    return SqlResult.ok(null,newObj);
                }

                Long recptLineId = oldObj == null? newObj.getAssembleIdToItemRecptLineId():oldObj.getAssembleIdToItemRecptLineId();
                //获取组装入库的入库记录
                WmItemRecptLine recptLine = itemRecptLineService.getById(recptLineId);
                if (recptLine.getIsInStock().equals("2")){
                    return SqlResult.ok(null,null);
                }
                //获取产品bom组成
                MdProductStatisticsBom bom = new MdProductStatisticsBom();
                bom.setItemId(recptLine.getItemId());
                QueryWrapper<MdProductStatisticsBom> typeBomQueryWrapper = new QueryWrapper<>(bom);
                List<MdProductStatisticsBom> pageList = list(typeBomQueryWrapper);
                if (pageList == null || pageList.size() == 0){
                    return SqlResult.error(recptLine.getItemName()+"不支持组装",newObj);
                }

                HashMap<String, BigDecimal> hashMap = new HashMap<>();
                for (int j = 0; j < pageList.size(); j++) {
                    hashMap.put(String.valueOf(pageList.get(j).getStatisticsId()),pageList.get(j).getQuantity());
                }

                //获取已经领料的记录
                List<ZuZhuangUse> useList = getBaseMapper().findZuZhuangUse(recptLineId);

                boolean isTrue = false;
                boolean isAllContent = false;
                if (useList != null && useList.size() > 0){
                    isTrue = true;
                    isAllContent = true;
                }
                String msg = "";
                if (useList.size() != pageList.size()){
                    isAllContent = false;
                }
                //对比比较
                int allCount = 0;
                for (int i = 0;i < useList.size();i++){
                    ZuZhuangUse use = useList.get(i);
                    allCount += use.getQuantity().floatValue();
                    BigDecimal bigDecimal = hashMap.get(String.valueOf(use.getProcessProductId()));
                    if (bigDecimal == null){
                        isTrue = false;
                        isAllContent = false;
                        msg = recptLine.getItemName()+" 产品组装用不到物料" + use.getItemName();
                        break;
                    }
                    float need = bigDecimal.floatValue()*recptLine.getQuantityRecived().floatValue();
                    if (use.getQuantity().floatValue() > need){
                        isTrue = false;
                        isAllContent = false;
                        msg =  use.getItemName()+" 用料过多";
                        break;
                    }else if (use.getQuantity().floatValue() < need){
                        isAllContent = false;
                    }
                }
                if (!isTrue){
                    return SqlResult.error(msg,null);
                }
                if (isAllContent){
                    recptLine.setIsInStock("4");
                    itemRecptLineService.updateById(recptLine);
                }else {
                    if (allCount == 0){
                        recptLine.setIsInStock("0");
                    }else {
                        recptLine.setIsInStock("3");
                    }
                    itemRecptLineService.updateById(recptLine);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return SqlResult.error(this.getClass().toString(),e);
        }
        return SqlResult.ok(null,newObj);
    }

    public List<MdProductStatisticsBom> findBomNotMaterial(Long itemId){
        return getBaseMapper().findBomNotMaterial(itemId);
    };


}
